package com.tsfyun.scm.gateway.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.tsfyun.scm.gateway.constant.LimitConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.netty.ByteBufFlux;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;

/**
 *   验证码的生成（无法返回图片流，作废）
 */
@Deprecated
@RestController
@Slf4j
@RequestMapping("/kaptcha")
public class KaptchaController {

    /**
     * 1、验证码工具
     */
    @Autowired
    private DefaultKaptcha kaptcha;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${frequency.exipre:60}")
    private Integer frequencyExpireTime;

    /**
     * 生成验证码
     * @throws Exception
     */
    @RequestMapping("/jpg")
    public void getKaptcha(ServerWebExchange exchange)
            throws Exception {
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        String token = exchange.getRequest().getHeaders().getFirst("token");
        String rightCode = kaptcha.createText();
        redisTemplate.opsForValue().set(LimitConstant.FREQUENCY_VALIDATE_CODE + token, rightCode,
                frequencyExpireTime, TimeUnit.SECONDS);

        BufferedImage challenge = kaptcha.createImage(rightCode);
        ImageIO.write(challenge, "jpg", jpegOutputStream);
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        serverHttpResponse.getHeaders().add("Cache-Control", "no-store");
        serverHttpResponse.getHeaders().add("Pragma", "no-cache");
        serverHttpResponse.getHeaders().add("Expires", "0");
        serverHttpResponse.getHeaders().add("Content-Type","image/jpeg");
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(jpegOutputStream.toByteArray());
        exchange.getResponse().writeAndFlushWith(Flux.just(ByteBufFlux.just(buffer)));
    }

}

